<template>
  <view>
    <view class="uni-header">
      <view class="uni-group">
        <view class="uni-title"></view>
        <view class="uni-sub-title"></view>
      </view>
      <view class="uni-group">
        <!-- <input class="uni-search" type="text" v-model="query" @confirm="search" placeholder="请输入搜索内容" /> -->
        <lay-button type="normal" @click="search" size="sm">
          <i class="layui-icon layui-icon-refresh-three marginR5"></i>刷新
        </lay-button>
        <download-excel class="hide-on-phone marginL10" :fields="exportExcel.fields" :data="exportExcelData" :type="exportExcel.type" :name="exportExcel.filename">
          <lay-button size="sm" type="danger">
            <i class="layui-icon layui-icon-export marginR5"></i>导出 Excel
          </lay-button>
        </download-excel>
      </view>
    </view>
    <view class="uni-container">
      <unicloud-db ref="udb" :collection="collectionList" :where="where" page-data="replace"
        :orderby="orderby" :getcount="true" :page-size="options.pageSize" :page-current="options.pageCurrent"
        v-slot:default="{data,pagination,loading,error,options}" :options="options" loadtime="manual" @load="onqueryload">
        <uni-table ref="table" :loading="loading" :emptyText="error.message || '没有更多数据'" border stripe type="selection" @selection-change="selectionChange">
          <uni-tr>
            <uni-th align="center" filter-type="search" @filter-change="filterChange($event, 'order_id')" sortable @sort-change="sortChange($event, 'order_id')">订单编号</uni-th>
            <uni-th align="center">所属学校</uni-th>
            <uni-th align="center" width="300px">商品信息</uni-th>
            <uni-th align="center" filter-type="search" @filter-change="filterChange($event, 'order_real_all_money')" sortable @sort-change="sortChange($event, 'order_real_all_money')">订单总金额</uni-th>
            <uni-th align="center">接单骑手</uni-th>
            <uni-th align="center" filter-type="select" :filter-data="options.filterData.order_status_localdata" @filter-change="filterChange($event, 'order_status')">订单状态</uni-th>
            <uni-th align="center">下单时间</uni-th>
            <uni-th align="center">操作</uni-th>
          </uni-tr>
          <uni-tr v-for="(item,index) in data" :key="index">
            <uni-td align="center">{{item.order_id}}</uni-td>
            <uni-td align="center">{{item.school_id && item.school_id[0] && item.school_id[0].text}}</uni-td>
            <uni-td align="left">
              <lay-tooltip :content="getProductName(item)" :isDark="false">
                <div style="display: -webkit-box;-webkit-box-orient: vertical;-webkit-line-clamp: 3;overflow: hidden;">
                {{ getProductName(item) }}
              </div>
              </lay-tooltip>
            </uni-td>
            <uni-td align="center">
              <div>{{ +BigJs(item.order_real_all_money).div(100) }}元</div>
            </uni-td>
            <uni-td align="center">
                {{item.rider_id && item.rider_id[0] && item.rider_id[0].text}}
            </uni-td>
            <uni-td align="center">
              <lay-tooltip content="点击开始更新订单支付状态" :isDark="false">
                  <div 
                  @click="getOrderNewStatus(item)"
                  style="cursor: pointer;"
                >
                  {{options.order_status_valuetotext[item.order_status]}}
                </div>
              </lay-tooltip>
            </uni-td>
            <uni-td align="center">
              <uni-dateformat :threshold="[0, 0]" :date="item.create_date"></uni-dateformat>
            </uni-td>
            <uni-td align="center">
              <view class="uni-group">
                <lay-button type="primary" size="sm" @click="layerViewDetailOrder(item)">
                  <i class="layui-icon layui-icon-snowflake marginR5"></i>详细
                </lay-button>
                <lay-button 
                  type="danger" size="sm" 
                  @click="layerOrderRefund({
                    ...item,
                    refund_module:`foodTakeout`
                  })" 
                  v-if="item.order_status!=6&&item.order_status!=8&&item.order_status!=9&&item.order_status!=10"
                  >
                <i class="layui-icon layui-icon-rmb marginR5"></i>退款
              </lay-button>
              </view>
            </uni-td>
          </uni-tr>
        </uni-table>
        <view class="uni-pagination-box">
          <uni-pagination show-icon :page-size="pagination.size" v-model="pagination.current" :total="pagination.count" @change="onPageChanged" />
        </view>
      </unicloud-db>
    </view>
  </view>
</template>

<script>
  import { enumConverter, filterToWhere } from '../../js_sdk/validator/food-order-list.js';
  import BigJs from 'big.js'
  import publicLayerCom from '../layer-com/index.js'
  import {layerOrderRefund} from '@/components/layer-components/order-refund/layer-com.js'
  import {showModalDbError} from '@/utils/helper.js'
  import {store} from '@/uni_modules/uni-id-pages/common/store.js'

  const db = uniCloud.database()
  const adminOrderManage = uniCloud.importObject(`admin-order-manage`,{customUI:true})

  // 表查询配置
  const dbOrderBy = 'create_date desc' // 排序字段
  const dbSearchFields = [] // 模糊搜索字段，支持模糊搜索的字段列表。联表查询格式: 主表字段名.副表字段名，例如用户表关联角色表 role.role_name
  // 分页配置
  const pageSize = 20
  const pageCurrent = 1

  const orderByMapping = {
    "ascending": "asc",
    "descending": "desc"
  }

  export default {
    data() {
      return {
        collectionList: [ 
          db.collection('food-order-list').where(`merchant_id=='${store.userInfo.merchant_id}'`).field('create_date,order_id,school_id,user_id,user_address_id,user_address_text,user_remark,product_list,expected_delivery_min,expected_delivery_max,expected_delivery_text,order_end_time,order_out_time,order_tips_money,order_all_money,order_real_all_money,merchat_order_get_time,merchat_order_status,rider_order_get_status,rider_order_get_time,rider_id,order_status').getTemp(),
          db.collection('admin-school-list').field('school_name as text, _id').getTemp(),
          db.collection('admin-user-address').field('address as text, _id').getTemp(),
          db.collection('uni-id-users').field('_id as text, _id').getTemp() 
        ],
        query: '',
        where: '',
        orderby: dbOrderBy,
        orderByFieldName: "",
        selectedIndexs: [],
        options: {
          pageSize,
          pageCurrent,
          filterData: {
            "merchat_order_status_localdata": [
              {
                "value": 0,
                "text": "待接单"
              },
              {
                "value": 1,
                "text": "已接单"
              },
              {
                "value": 2,
                "text": "已取消"
              }
            ],
            "order_status_localdata": [
              {
                "value": 0,
                "text": "待接单"
              },
              {
                "value": 1,
                "text": "已接单"
              },
              {
                "value": 2,
                "text": "已取货"
              },
              {
                "value": 3,
                "text": "派送中"
              },
              {
                "value": 4,
                "text": "已完成"
              },
              {
                "value": 5,
                "text": "已失败"
              },
              {
                "value": 6,
                "text": "已取消"
              },
              {
                "value": 7,
                "text": "已超时"
              },
              {
                "value": 8,
                "text": "待付款"
              },
              {
                "value": 9,
                "text": "退款/售后"
              },
              {
                "value": 10,
                "text": "支付超时，订单取消"
              }
            ]
          },
          ...enumConverter
        },
        imageStyles: {
          width: 64,
          height: 64
        },
        exportExcel: {
          "filename": "food-order-list.xls",
          "type": "xls",
          "fields": {
            "订单编号": "order_id",
            "所属学校": "school_id",
            "所属商户": "merchant_id",
            "所属用户": "user_id",
            "用户地址": "user_address_id",
            "完整送货地址": "user_address_text",
            "订单备注": "user_remark",
            "商品列表": "product_list",
            "最小时间": "expected_delivery_min",
            "最大时间": "expected_delivery_max",
            "预计送达时间": "expected_delivery_text",
            "订单结束时间": "order_end_time",
            "订单超时时间": "order_out_time",
            "订单小费": "order_tips_money",
            "订单合计金额": "order_all_money",
            "订单总金额": "order_real_all_money",
            "商家接单时间": "merchat_order_get_time",
            "商家接单状态": "merchat_order_status",
            "骑手是否接单": "rider_order_get_status",
            "骑手接单时间": "rider_order_get_time",
            "接单骑手": "rider_id",
            "订单状态": "order_status",
            "订单完成回执": "order_receipt",
            "发送给第三方订单的编号": "three_pay_order_id",
            "第三方订单支付状态回调的编号": "three_pay_transaction_id"
          }
        },
        exportExcelData: []
      }
    },
    onLoad() {
      this._filter = {}
    },
    mounted() {
      this.search();
    },
    methods: {
      ...publicLayerCom,
      layerOrderRefund,
      BigJs(args){
        return new BigJs(args)
      },
      getProductName(item){
        const productAndStore = item.product_list[0];
        return productAndStore.check_result.map(it=>{
          return `${it.product.product_name}x${it.count}`
        }).join(`、`)
      },
      async getOrderNewStatus(item){
        try {
            uni.showLoading({ title: `正在更新`,mask:true})
            const results =await adminOrderManage.queryKnowOrderIdPayStatus(item.three_pay_order_id)
            uni.hideLoading(); 
            if(results.myErrCode!==0){
              return showModalDbError(results)
            }
            uni.showToast({
              title: '更新成功'
            })
            if(results.data.status!==-1 && results.data.status != item.order_status){
              this.$refs.udb.loadData(false)
            }
        } catch (error) {
          console.error(error)
          uni.hideLoading(); 
        }

      },


      onqueryload(data) {
        this.exportExcelData = data
      },
      getWhere() {
        const query = this.query.trim()
        if (!query) {
          return ''
        }
        const queryRe = new RegExp(query, 'i')
        return dbSearchFields.map(name => queryRe + '.test(' + name + ')').join(' || ')
      },
      search() {
        const newWhere = this.getWhere()
        this.where = newWhere
        this.$nextTick(() => {
          this.loadData()
        })
      },
      loadData(clear = true) {
        this.$refs.udb.loadData({
          clear
        })
      },
      onPageChanged(e) {
        this.selectedIndexs.length = 0
        this.$refs.table.clearSelection()
        this.$refs.udb.loadData({
          current: e.current
        })
      },
      navigateTo(url, clear) {
        // clear 表示刷新列表时是否清除页码，true 表示刷新并回到列表第 1 页，默认为 true
        uni.navigateTo({
          url,
          events: {
            refreshData: () => {
              this.loadData(clear)
            }
          }
        })
      },
      // 多选处理
      selectedItems() {
        var dataList = this.$refs.udb.dataList
        return this.selectedIndexs.map(i => dataList[i]._id)
      },
      // 批量删除
      delTable() {
        this.$refs.udb.remove(this.selectedItems(), {
          success:(res) => {
            this.$refs.table.clearSelection()
          }
        })
      },
      // 多选
      selectionChange(e) {
        this.selectedIndexs = e.detail.index
      },
      confirmDelete(id) {
        this.$refs.udb.remove(id, {
          success:(res) => {
            this.$refs.table.clearSelection()
          }
        })
      },
      sortChange(e, name) {
        this.orderByFieldName = name;
        if (e.order) {
          this.orderby = name + ' ' + orderByMapping[e.order]
        } else {
          this.orderby = ''
        }
        this.$refs.table.clearSelection()
        this.$nextTick(() => {
          this.$refs.udb.loadData()
        })
      },
      filterChange(e, name) {
        if(name==`order_real_all_money`){
          try {
            const value =+BigJs(e.filter).times(100) 
            e ={
              filter:[value,value],
              filterType:`range`
            } 
          } catch (error) {}
        }
        this._filter[name] = {
          type: e.filterType,
          value: e.filter
        }
        let newWhere = filterToWhere(this._filter, db.command)
        if (Object.keys(newWhere).length) {
          this.where = newWhere
        } else {
          this.where = ''
        }
        this.$nextTick(() => {
          this.$refs.udb.loadData()
        })
      }
    }
  }
</script>

<style>
</style>
